package com.cgbl.cg.ui.mine

import android.os.Bundle
import android.view.View
import android.widget.ImageView
import com.alibaba.android.arouter.facade.annotation.Route
import com.blankj.utilcode.util.FragmentUtils
import com.cgbl.cg.BR
import com.cgbl.cg.R
import com.cgbl.cg.databinding.AppActivityCourseProfileBinding
import com.cgbl.cg.vm.mine.CourseProfileViewModel
import com.google.android.exoplayer2.C
import com.google.android.exoplayer2.SeekParameters
import com.robot.base.base.activity.GLBaseActivity
import com.robot.base.configs.AppConstants
import com.robot.base.model.CourseInfoFileBean
import com.robot.base.util.LiveDataEventManager
import com.shuyu.gsyvideoplayer.GSYVideoManager
import com.shuyu.gsyvideoplayer.builder.GSYVideoOptionBuilder
import com.shuyu.gsyvideoplayer.listener.GSYSampleCallBack
import com.shuyu.gsyvideoplayer.model.VideoOptionModel
import com.shuyu.gsyvideoplayer.player.IjkPlayerManager
import com.shuyu.gsyvideoplayer.utils.Debuger
import com.shuyu.gsyvideoplayer.utils.OrientationUtils
import com.shuyu.gsyvideoplayer.video.StandardGSYVideoPlayer
import com.shuyu.gsyvideoplayer.video.base.GSYVideoPlayer
import tv.danmaku.ijk.media.exo2.Exo2PlayerManager
import tv.danmaku.ijk.media.exo2.IjkExo2MediaPlayer
import tv.danmaku.ijk.media.player.IjkMediaPlayer


@Route(path = AppConstants.Router.Mine.A_MINE_COURSE_PROFILE)
class CourseProfileActivity :
    GLBaseActivity<AppActivityCourseProfileBinding, CourseProfileViewModel>() {

    val courseProfileFragment = CourseProfileFragment()

    val courseDirectoryFragment = CourseDirectoryFragment()

    val courseCommentFragment = CourseCommentFragment()

    val courseFileFragment = CourseResourceFragment()

    var id = ""

    override fun onCreate(savedInstanceState: Bundle?) {
        // 设置一个exit transition
//        window.requestFeature(Window.FEATURE_CONTENT_TRANSITIONS)
//        window.addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS)
//        window.enterTransition = Explode()
//        window.exitTransition = Explode()
        super.onCreate(savedInstanceState)
    }

    override fun initComponents() {
        initView()
        viewModel.fetchCourseInfo(id)
    }

    private fun initView() {

        FragmentUtils.add(
            supportFragmentManager, listOf(
                courseProfileFragment,
                courseDirectoryFragment,
                courseCommentFragment,
                courseFileFragment
            ), R.id.fragment_container, 0
        )
    }

    override fun initViewObservable() {
        LiveDataEventManager.observerPaySuccessEvent(this) {
            viewModel.fetchCourseInfo(id)
        }

        LiveDataEventManager.observerPlayCourseEvent(this) {
            if (viewModel.isBuyField.get()) {
                initVideo(it.toString())
            }
        }
        viewModel.uc.courseInfoData.observe(this) {
            if (viewModel.isBuyField.get()) {
                initVideo(
                    it.infoChaptarVOS?.get(0)?.courseInfoChaptarPeriodVOS?.get(0)?.resourcePath
                        ?: ""
                )
            }
            courseProfileFragment.setCourseProfileData(it)
            courseDirectoryFragment.setCourseProfileData(it)
            courseCommentFragment.setCourseProfileData(it.id ?: "")
            courseFileFragment.setCourseProfileData(
                it.infoFileRespVOS as MutableList<CourseInfoFileBean>?, it.pay, it.id, "1"
            )
        }
        viewModel.uc.switchTabEvent.observe(this) {
            when (it) {
                CourseProfileViewModel.TAB_PROFILE -> {
                    FragmentUtils.showHide(
                        courseProfileFragment,
                        courseDirectoryFragment,
                        courseCommentFragment,
                        courseFileFragment
                    )
                }

                CourseProfileViewModel.TAB_DIRECTORY -> {
                    FragmentUtils.showHide(
                        courseDirectoryFragment,
                        courseProfileFragment,
                        courseCommentFragment,
                        courseFileFragment
                    )
                }

                CourseProfileViewModel.TAB_COMMENT -> {
                    FragmentUtils.showHide(
                        courseCommentFragment,
                        courseDirectoryFragment,
                        courseProfileFragment,
                        courseFileFragment
                    )
                }

                CourseProfileViewModel.TAB_FILE -> {
                    FragmentUtils.showHide(
                        courseFileFragment,
                        courseDirectoryFragment,
                        courseCommentFragment,
                        courseProfileFragment
                    )
                }
            }
        }
    }


    override fun initParam() {
        super.initParam()
        id = intent.getStringExtra(AppConstants.BundleKey.ID) ?: ""
    }


    override fun onPause() {
//        getCurPlay()?.onVideoPause()
        super.onPause()

    }

    override fun onResume() {
//        getCurPlay()?.onVideoResume(false)
        super.onResume()
    }

    override fun onDestroy() {
        super.onDestroy()
        if (isPlay) {
            getCurPlay()?.release()
        }
        //GSYPreViewManager.instance().releaseMediaPlayer();
        if (orientationUtils != null) orientationUtils?.releaseListener()
    }

    override fun initContentView(savedInstanceState: Bundle?): Int =
        R.layout.app_activity_course_profile

    override fun initVariableId(): Int = BR.viewModel
    private var curPlayer: StandardGSYVideoPlayer? = null
    private var itemPlayer: StandardGSYVideoPlayer? = null

    var orientationUtils: OrientationUtils? = null

    var isPlay = false

    var isFull = false

    var initPlay = false
    fun initVideo(filePath: String) {
        if (initPlay) {
            binding.videoItemPlayer.setUp(filePath, false, "File")
            binding.videoItemPlayer.startPlayLogic()
        } else {
            initPlay = true
            /***************rtsp 配置 */
            val videoOptionModel =
                VideoOptionModel(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "enable-accurate-seek", 1)
            val list: MutableList<VideoOptionModel> = ArrayList()
            list.add(videoOptionModel)
            GSYVideoManager.instance().optionModelList = list

            /// ijk rtmp
            /*VideoOptionModel videoOptionModel =
                    new VideoOptionModel(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "protocol_whitelist", "crypto,file,http,https,tcp,tls,udp,rtmp,rtsp");
            List<VideoOptionModel> list = new ArrayList<>();
            list.add(videoOptionModel);
            GSYVideoManager.instance().setOptionModelList(list);*/

            //增加封面

            /// ijk rtmp
            /*VideoOptionModel videoOptionModel =
                    new VideoOptionModel(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "protocol_whitelist", "crypto,file,http,https,tcp,tls,udp,rtmp,rtsp");
            List<VideoOptionModel> list = new ArrayList<>();
            list.add(videoOptionModel);
            GSYVideoManager.instance().setOptionModelList(list);*/

            //增加封面
//            val imageView = ImageView(this)
//            imageView.scaleType = ImageView.ScaleType.CENTER_CROP
//            imageView.setImageResource(R.mipmap.video_enlarge)

            //外部辅助的旋转，帮助全屏
            IjkPlayerManager.setLogLevel(IjkMediaPlayer.IJK_LOG_SILENT);
            //外部辅助的旋转，帮助全屏
            orientationUtils = OrientationUtils(this, binding.videoItemPlayer)
            //初始化不打开外部的旋转
            //初始化不打开外部的旋转
            orientationUtils!!.isEnable = false
            /**仅仅横屏旋转，不变直*/
            //orientationUtils.setOnlyRotateLand(true);

            //ProxyCacheManager.DEFAULT_MAX_SIZE = 1024 * 1024 * 1024 * 1024;
            //ProxyCacheManager.DEFAULT_MAX_COUNT = 8;

            /**仅仅横屏旋转，不变直 */
            //orientationUtils.setOnlyRotateLand(true);

            //ProxyCacheManager.DEFAULT_MAX_SIZE = 1024 * 1024 * 1024 * 1024;
            //ProxyCacheManager.DEFAULT_MAX_COUNT = 8;
            val header: MutableMap<String, String> = HashMap()
            header["ee"] = "33"
            header["allowCrossProtocolRedirects"] = "true"
            header["User-Agent"] = "GSY"
            val gsyVideoOption = GSYVideoOptionBuilder()
            gsyVideoOption
//                .setThumbImageView(imageView)
                .setIsTouchWiget(true).setRotateViewAuto(false) //仅仅横屏旋转，不变直
                //.setOnlyRotateLand(true)
                .setRotateWithSystem(false).setLockLand(true).setAutoFullWithSize(true)
                .setShowFullAnimation(false).setNeedLockFull(true).setUrl(filePath)
                .setMapHeadData(header).setCacheWithPlay(false).setSurfaceErrorPlay(false)
                .setVideoTitle("").setVideoAllCallBack(object : GSYSampleCallBack() {

                    override fun onPrepared(url: String, vararg objects: Any) {
                        Debuger.printfError("***** onPrepared **** " + objects[0])
                        Debuger.printfError("***** onPrepared **** " + objects[1])
                        super.onPrepared(url, *objects)

                        //开始播放了才能旋转和全屏
                        orientationUtils!!.isEnable = binding.videoItemPlayer.isRotateWithSystem
                        isPlay = true


                        //设置 seek 的临近帧。
                        if (binding.videoItemPlayer.gsyVideoManager.player is Exo2PlayerManager) {
                            (binding.videoItemPlayer.gsyVideoManager.player as Exo2PlayerManager).setSeekParameter(
                                SeekParameters.NEXT_SYNC
                            )
                            Debuger.printfError("***** setSeekParameter **** ")
                        }


                        //设置 seek 的临近帧。
                        if (binding.videoItemPlayer.gsyVideoManager.player is Exo2PlayerManager) {
                            val player =
                                binding.videoItemPlayer.gsyVideoManager.player.mediaPlayer as IjkExo2MediaPlayer
                            val mappedTrackInfo = player.trackSelector.currentMappedTrackInfo
                            if (mappedTrackInfo != null) {
                                for (i in 0 until mappedTrackInfo.rendererCount) {
                                    val rendererTrackGroups = mappedTrackInfo.getTrackGroups(i)
                                    if (C.TRACK_TYPE_AUDIO == mappedTrackInfo.getRendererType(i)) { //判断是否是音轨
                                        for (j in 0 until rendererTrackGroups.length) {
                                            val trackGroup = rendererTrackGroups[j]
                                            Debuger.printfError(
                                                "####### " + trackGroup.getFormat(0)
                                                    .toString() + " #######"
                                            )
                                        }
                                    }
                                }
                            }
                        }
                        if (binding.videoItemPlayer.currentPlayer.isIfCurrentIsFullscreen) {
                            GSYVideoManager.instance().setLastListener(binding.videoItemPlayer)
                        }
                    }

                    override fun onEnterFullscreen(url: String, vararg objects: Any) {
                        super.onEnterFullscreen(url, *objects)
                        Debuger.printfError("***** onEnterFullscreen **** " + objects[0]) //title
                        Debuger.printfError("***** onEnterFullscreen **** " + objects[1]) //当前全屏player
                    }

                    override fun onAutoComplete(url: String, vararg objects: Any) {
                        super.onAutoComplete(url, *objects)
                    }

                    override fun onClickStartError(url: String, vararg objects: Any) {
                        super.onClickStartError(url, *objects)
                    }

                    override fun onQuitFullscreen(url: String, vararg objects: Any) {
                        super.onQuitFullscreen(url, *objects)
                        Debuger.printfError("***** onQuitFullscreen **** " + objects[0]) //title
                        Debuger.printfError("***** onQuitFullscreen **** " + objects[1]) //当前非全屏player

                        // ------- ！！！如果不需要旋转屏幕，可以不调用！！！-------
                        // 不需要屏幕旋转，还需要设置 setNeedOrientationUtils(false)
                        if (orientationUtils != null) {
                            orientationUtils!!.backToProtVideo()
                        }
                    }
                }).setLockClickListener { view, lock ->
                    if (orientationUtils != null) {
                        //配合下方的onConfigurationChanged
                        orientationUtils!!.isEnable = !lock
                    }
                }.setGSYVideoProgressListener { progress, secProgress, currentPosition, duration ->
                    Debuger.printfLog(
                        " progress $progress secProgress $secProgress currentPosition $currentPosition duration $duration"
                    )
                }.build(binding.videoItemPlayer)

            binding.videoItemPlayer.findViewById<ImageView>(R.id.iv_need).setOnClickListener {
                GSYVideoManager.instance().isNeedMute = !GSYVideoManager.instance().isNeedMute
                if (GSYVideoManager.instance().isNeedMute) {
                    binding.videoItemPlayer.findViewById<ImageView>(R.id.iv_need)
                        .setImageResource(R.mipmap.app_video_need_un)
                } else {
                    binding.videoItemPlayer.findViewById<ImageView>(R.id.iv_need)
                        .setImageResource(R.mipmap.app_video_need)
                }
            }

            //增加title
            binding.videoItemPlayer.titleTextView.visibility = View.GONE
            binding.videoItemPlayer.backButton.visibility = View.GONE
            binding.videoItemPlayer.fullscreenButton.setOnClickListener(View.OnClickListener { //直接横屏
                // ------- ！！！如果不需要旋转屏幕，可以不调用！！！-------
                // 不需要屏幕旋转，还需要设置 setNeedOrientationUtils(false)
                orientationUtils!!.resolveByClick()

                //第一个true是否需要隐藏actionbar，第二个true是否需要隐藏statusbar
                binding.videoItemPlayer.startWindowFullscreen(this, true, true)
            })
            //循环
            //binding.videoItemPlayer.setLooping(true);
            binding.videoItemPlayer.isNeedLockFull = false

            binding.videoItemPlayer.speed = 1f;
        }
    }

    private fun getCurPlay(): GSYVideoPlayer? {
        return if (binding.videoItemPlayer.fullWindowPlayer != null) {
            binding.videoItemPlayer.fullWindowPlayer
        } else binding.videoItemPlayer
    }

    fun clearCache() {
        if (curPlayer != null) {
            curPlayer?.currentPlayer?.clearCurrentCache()
        }
    }

//    fun isFull(): Boolean {
//        return isFull
//    }

    /**************************支持全屏重力全屏的部分**************************/

    /**************************支持全屏重力全屏的部分 */
    /**
     * 列表时是否需要支持重力旋转
     *
     * @return 返回true为支持列表重力全屏
     */
    fun getListNeedAutoLand(): Boolean {
        return true
    }

    private fun resolveFull() {
        if (getListNeedAutoLand() && orientationUtils != null) {
            //直接横屏
            // ------- ！！！如果不需要旋转屏幕，可以不调用！！！-------
            // 不需要屏幕旋转，还需要设置 setNeedOrientationUtils(false)
            orientationUtils?.resolveByClick()
        }
    }

    fun onPrepared() {
        if (orientationUtils == null) {
            return
        }
        //开始播放了才能旋转和全屏
        orientationUtils?.isEnable = true
    }
}